package com.hooya.fa.eu.biz.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.hooya.fa.eu.api.bo.stk.BuyRecordBO;
import com.hooya.fa.eu.api.bo.stk.HistoryBelongsBO;
import com.hooya.fa.eu.api.bo.stk.SellRecordBO;
import com.hooya.fa.eu.api.enums.CkEnum;
import com.hooya.fa.eu.api.util.DateExtUtil;
import com.hooya.fa.eu.biz.dao.entity.*;
import com.hooya.fa.eu.biz.dao.entity.rxh.MetaStore;
import com.hooya.fa.eu.biz.dao.manager.AddEntityManager;
import com.hooya.fa.eu.biz.dao.manager.GeneratorEntityManager;
import com.hooya.fa.eu.biz.dao.manager.special.*;
import com.hooya.fa.eu.biz.dao.mapper.TempRestorationMapper;
import com.hooya.fa.eu.biz.dao.repository.TempKcjlDailyRepository;
import com.hooya.fa.eu.biz.dao.repository.TempPkpyRepository;
import com.hooya.fa.eu.biz.dao.repository.TempXsjlRelationRepository;
import com.hooya.fa.eu.biz.dao.repository.TempZyjlRelationRepository;
import com.hooya.fa.eu.biz.service.*;
import com.hooya.integrated.common.core.util.BeanCopyUtils;
import com.hooya.integrated.common.core.util.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.hooya.fa.eu.api.constant.DictConstant.DICT_PREFIX;

/**
 * @Description 审计补充订单服务实现
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/10/16
 * @Version 1.1.0
 */
@Slf4j
@Service
@DS("fa_eu")
@RequiredArgsConstructor
public class EuSupplementOrderServiceImpl implements EuSupplementOrderService {

    private final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    private final EuSourceDataService euSourceDataService;

    private final DictRelationService dictRelationService;

    private final StkCollectionService stkCollectionService;

    private final TempRelationService tempRelationService;

    private final SellDeliveryManager sellDeliveryManager;

    private final JcDataManager jcDataManager;

    private final JcHisBelongsManager jcHisBelongsManager;

    private final XsDataManager xsDataManager;

    private final PkpyManager pkpyManager;

    private final FinalDataManager finalDataManager;

    private final AddEntityManager addEntityManager;

    private final GeneratorEntityManager generatorEntityManager;

    private final TempPkpyRepository tempPkpyRepository;

    private final TempKcjlDailyRepository tempKcjlDailyRepository;

    private final TempZyjlRelationRepository tempZyjlRelationRepository;

    private final TempXsjlRelationRepository tempXsjlRelationRepository;

    private final TempRestorationMapper tempRestorationMapper;

    @Override
    @DSTransactional
    public void containerOrder(List<String> fpInvoiceList, Integer xsDeleteNum) {
        List<BuyRecordBO> warehousingList = euSourceDataService.getWarehousingListByDate(null, null);
        List<BuyRecordBO> addWarehousingList = warehousingList.stream()
                .filter(l -> fpInvoiceList.contains(l.getHthm())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(addWarehousingList)) {
            return;
        }
        List<BuyRecordBO> belongsList = addWarehousingList.stream().filter(l -> StringUtils.isBlank(l.getBelongs()))
                .collect(Collectors.toList());
        StringJoiner sj = new StringJoiner(",");
        if (!CollectionUtils.isEmpty(belongsList)) {
            Map<String, String> abnormalBelongsMap =
                    RedisUtils.hmget(DICT_PREFIX + CkEnum.ABNORMAL_BELONGS_MAP.getName());
            belongsList.forEach(l -> {
                String belongs = abnormalBelongsMap.get(l.getHthm());
                if (StringUtils.isBlank(belongs)) {
                    sj.add(l.getHthm());
                    return;
                }
                l.setBelongs(belongs);
            });
        }
        if (StringUtils.isNotBlank(sj.toString())) {
            throw new RuntimeException(String.format("请维护发票号【%s】的货权", sj));
        }
        Map<String, List<BuyRecordBO>> supplementFpInvoiceMap = addWarehousingList.stream()
                .collect(Collectors.groupingBy(BuyRecordBO::getHthm));

        //------数据全部放置下月份执行，并记录恢复表------
        List<TempPkpy> pkpyRes = new ArrayList<>();
        Map<String, List<String>> zySheetNumberMap = new HashMap<>();
        Map<String, List<String>> xsSheetNumberMap = new HashMap<>();
        supplementFpInvoiceMap.forEach((invoiceNumber, l) -> {
            String fpDate = l.get(0).getSourceDate();
            //优化查询少几次
            Map<String, List<BuyRecordBO>> groupMap = l.stream()
                    .collect(Collectors.groupingBy(m -> m.getPlace() + "_" + m.getBelongs()));
            for (String key : groupMap.keySet()) {
                String place = key.split("_")[0];
                String belongs = key.split("_")[1];
                List<String> skuList = groupMap.get(key).stream().map(BuyRecordBO::getCpbh).collect(Collectors.toList());
                //盘亏的数量进行盘盈
                List<TempPkpy> pkpyList = tempPkpyRepository.getByCondition(place, belongs, fpDate, skuList);
                Map<String, List<TempPkpy>> cpbMap = pkpyList.stream()
                        .collect(Collectors.groupingBy(m -> m.getCpbh() + "_" + m.getPlace() + m.getBelongs()));
                for (String k : cpbMap.keySet()) {
                    String sku = k.split("_")[0];
                    int sl = cpbMap.get(k).stream().mapToInt(TempPkpy::getSl).sum();
                    int num = -sl;
                    pkpyRes.add(TempPkpy.builder().cpbh(sku).sl(num).place(place).belongs(belongs)
                            .date(DateExtUtil.getCurMonthLastDay(null)).createTime(new Date()).build());
                }
                //对应zy的delete与change需要恢复（需要走流程）
                List<TempZyjlDelete> zyDeleteList = tempZyjlRelationRepository
                        .getDeleteListByCondition(place, fpDate, skuList);
                List<TempZyjlChange> zyChangeList = tempZyjlRelationRepository
                        .getChangeListByCondition(place, fpDate, skuList);
                List<String> zySheetNumbers = zyDeleteList.stream().map(TempZyjlDelete::getSheetNumber).collect(Collectors.toList());
                zySheetNumbers.addAll(zyChangeList.stream().map(TempZyjlChange::getSheetNumber).collect(Collectors.toList()));
                if (CollectionUtils.isEmpty(zySheetNumberMap.get(fpDate))) {
                    zySheetNumberMap.put(fpDate, zySheetNumbers);
                } else {
                    zySheetNumberMap.get(fpDate).addAll(zySheetNumbers);
                }
                //销售拒绝、销售删除的进行校验恢复（需要走流程）
                List<TempXsjlDelete> xsDeleteList = tempXsjlRelationRepository
                        .getDeleteListByCondition(place, belongs, fpDate, skuList);
                List<TempXsjlAbnormal> xsAbnormalList = tempXsjlRelationRepository
                        .getAbnormalListByCondition(place, fpDate, skuList);
                List<String> xsSheetNumbers = xsDeleteList.stream().map(TempXsjlDelete::getSheetNumber).collect(Collectors.toList());
                xsSheetNumbers.addAll(xsAbnormalList.stream().map(TempXsjlAbnormal::getSheetNumber).collect(Collectors.toList()));
                if (CollectionUtils.isEmpty(xsSheetNumberMap.get(fpDate))) {
                    xsSheetNumberMap.put(fpDate, xsSheetNumbers);
                } else {
                    xsSheetNumberMap.get(fpDate).addAll(xsSheetNumbers);
                }
            }
        });
        //------------------- 准备原数据 -------------------
        //获取补单原数据的结束时间
        //（即补单的数据流失了几个月，例柜子是2024-06-06，当前时间为24年10月，但程序跑异常单时为11月份，所以回溯时间则为0601 - 1001）
        String endDate = DateExtUtil.getBeforeNMonthFirstDay(null, 1);
        Map<String, List<BuyRecordBO>> zyMap = new HashMap<>();
//        Map<String, List<SellRecordBO>> sellDeliveryList = new HashMap<>();
        List<SellRecordBO> sellDeliveryList = new ArrayList<>();
        //即补异常单数据的日期【按照上述例子则是2024-10-31，补在最后一天】
        String lastMonthLastDay = DateExtUtil.getBeforeNMonthLastDay(null, 1);
        log.info("补单截止日期：" + lastMonthLastDay);
        //店铺公司字典
        List<MetaStore> metaStoreList = dictRelationService.getMetaStoreList();
        Map<String, String> storeMap = metaStoreList.stream().
                collect(Collectors.toMap(m -> m.getStore().toLowerCase(), MetaStore::getCorp));
        //fba国家列表
        List<String> fbaCountryList = euSourceDataService.getFbaCountryList();
        //虚拟仓库字典
        List<PlaceMatchDict> placeMatchDictList = dictRelationService.getPlaceMatchList();
        Map<String, PlaceMatchDict> placeMatchDictMap = placeMatchDictList.stream()
                .collect(Collectors.toMap(PlaceMatchDict::getVirtualWhId, i -> i));
        if (MapUtil.isNotEmpty(zySheetNumberMap)) {
            zySheetNumberMap.forEach((date, l) -> {
                if (!CollectionUtils.isEmpty(l)) {
                    String startDate = DateExtUtil.getCurMonthFirstDay(LocalDate.parse(date));
                    List<BuyRecordBO> list = euSourceDataService.getZyListByDateAndSheetNumber(startDate, endDate, l);
                    list.forEach(m -> m.setHtrq(lastMonthLastDay));
                    zyMap.put(lastMonthLastDay, list);
                }
            });
        }

        if (MapUtil.isNotEmpty(xsSheetNumberMap)) {
            xsSheetNumberMap.forEach((date, l) -> {
                if (!CollectionUtils.isEmpty(l)) {
                    List<SellRecordBO> sellList = new LinkedList<>();
                    String startDate = DateExtUtil.getCurMonthFirstDay(LocalDate.parse(date));
                    List<SellRecordBO> sellRecordList = euSourceDataService.getSellListByDateAndSheetNumber(startDate, endDate, l);
                    List<String> whIds = euSourceDataService.getWhIdByTimeGet(startDate, endDate);
                    List<SellRecordBO> deliveryGoodsList = euSourceDataService
                            .getDeliveryGoodsListByDateAndSheetNumber(startDate, endDate, whIds, l);
                    sellDeliveryManager.getEligibleSellDeliveryData(sellRecordList, deliveryGoodsList,
                            sellList, placeMatchDictMap, storeMap, fbaCountryList);
                    sellList.stream().distinct().forEach(m -> m.setOrderDate(lastMonthLastDay));
                    sellDeliveryList.addAll(sellList);
                }
            });
        }
        //---------------------------- 转运销售处理 ----------------------------

        //处理数据（时间和创建时间）
        Date createTime = new Date();
        log.info("补单时间：" + createTime);

        //*************** 转运 ***************
        List<BuyRecordBO> recordList = new LinkedList<>();
        //fba仓库
        Map<String, String> fbaCkMap = RedisUtils.hmget(DICT_PREFIX + CkEnum.FBA_CK_MAP.getName());
        //进仓公司字典
        Map<String, String> metaWarehouseMap = dictRelationService.getMetaWarehouseMap();
        //warehousingList进仓数据的处理
        jcDataManager.dealSourceJcData(df, warehousingList, recordList, placeMatchDictMap);
        //修改历史进仓货权，并整合数据
        List<HistoryBelongsBO> allHisBelongsList =
                jcHisBelongsManager.editJcHisBelongsAndIntegration(recordList);
        //fba货权信息(做筛选优化用)
        List<HistoryBelongsBO> fbaBelongsList =
                jcHisBelongsManager.getFbaJcHisBelongsData(df, lastMonthLastDay, allHisBelongsList, fbaCkMap);
        List<BuyRecordBO> fbaHisJcZy = BeanCopyUtils.copyListProperties(fbaBelongsList, BuyRecordBO::new);
        //总的买卖记录
        List<TradeRecord> tradeRecordList = new LinkedList<>();
        List<TempKcjlDaily> inventoryList = tempRelationService.getOpeningInventory(lastMonthLastDay, null)
                .stream().filter(l -> !l.getPlace().equals("EU07")).collect(Collectors.toList());
        StringBuffer remark = new StringBuffer();
        //remark 记录
        remark.append("柜子补单发发票号【" + String.join(",", fpInvoiceList) + "】\n");
        remark.append("原始库存: \n");
        for (BuyRecordBO bo : addWarehousingList) {
            List<TempKcjlDaily> kcjlList = inventoryList.stream().filter(l -> l.getBelongs().equals(bo.getBelongs()) &&
                            l.getPlace().equals(bo.getPlace()) && l.getCpbh().equals(bo.getCpbh()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(kcjlList)) {
                remark.append(bo.getCpbh()).append("-").append(bo.getPlace()).append("-")
                        .append(bo.getBelongs()).append(":").append("暂无库存; \n");
            } else {
                if (kcjlList.size() > 1) {
                    log.info("库存条数大于1");
                }
                remark.append(kcjlList.get(0).getCpbh()).append("-").append(kcjlList.get(0).getPlace()).append("-")
                        .append(kcjlList.get(0).getBelongs()).append(":").append(kcjlList.get(0).getSl()).append("; \n");
            }
        }
        //需要进行删除的转运数据(转运中，库存不存在，进仓不存在，转运中转入不存在（非fba逻辑）)
        List<TempZyjlDelete> tempZyjlDeleteList = new ArrayList<>();
        //总的进仓记录
        List<TempJcjl> tempJcjlList = new LinkedList<>();
        //总的转运记录
        List<TempZyjl> tempZyjlList = new LinkedList<>();
        //变更的转运记录(每轮循环结束，将相同条件合并，数量相加，以防万一)
        List<TempZyjlChange> zyjlChangeList = new LinkedList<>();
        List<BuyRecordBO> deleteZyRecord = new LinkedList<>();
        stkCollectionService.dealWithJcZyData(lastMonthLastDay, fbaCkMap, new HashMap<>(), zyMap, inventoryList, tradeRecordList,
                tempJcjlList, tempZyjlList, zyjlChangeList, fbaHisJcZy, metaWarehouseMap, deleteZyRecord, pkpyRes);
        if (!CollectionUtils.isEmpty(deleteZyRecord)) {
            tempZyjlDeleteList.addAll(BeanCopyUtils.copyListProperties(deleteZyRecord, TempZyjlDelete::new));
        }
        //由于上述inventoryList不作为更新数据得依据，所以需要找出转入与转出，进行手动更新
        if (!CollectionUtils.isEmpty(tempZyjlList)) {
            for (TempZyjl zyjl : tempZyjlList) {
                //转出库存
                TempKcjlDaily zckc = inventoryList.stream().filter(l -> l.getCpbh().equals(zyjl.getCpbh()) &&
                        l.getPlace().equals(zyjl.getZcck()) && l.getBelongs().equals(zyjl.getFrombelongs()) &&
                        l.getDate().equals(lastMonthLastDay)).findFirst().orElse(null);
                if (Objects.nonNull(zckc)) {
                    zckc.setSl(zckc.getSl() - zyjl.getCgsl());
                    tempKcjlDailyRepository.updateSl(zckc, lastMonthLastDay);
                } else {
                    log.info(zyjl.getCpbh() + "-" + zyjl.getZcck() + "-" + zyjl.getFrombelongs() + "无库存");
                }
                //转入库存
                TempKcjlDaily zrkc = inventoryList.stream().filter(l -> l.getCpbh().equals(zyjl.getCpbh()) &&
                        l.getPlace().equals(zyjl.getZlck()) && l.getBelongs().equals(zyjl.getTobelongs()) &&
                        l.getDate().equals(lastMonthLastDay)).findFirst().orElse(null);
                if (Objects.nonNull(zrkc)) {
                    zrkc.setSl(zrkc.getSl() + zyjl.getCgsl());
                    tempKcjlDailyRepository.updateSl(zrkc, lastMonthLastDay);
                } else {
                    //新增
                    TempKcjlDaily daily = generatorEntityManager.genTempKcjlDaily(zyjl.getCpbh(), zyjl.getTobelongs(),
                            zyjl.getZlck(), zyjl.getCgsl(), lastMonthLastDay);
                    daily.setCreateTime(createTime);
                    tempKcjlDailyRepository.insertEntity(daily);
                }
            }
        }

        //*************** 销售（暂时不加退货逻辑【除非有相关退货数据】）***************
        List<TempXsjl> tempXsjlList = new LinkedList<>();
        List<TempXsjlAbnormal> tempXsjlAbnormalList = new LinkedList<>();
        //inventoryList拷贝，用于后续盘亏盘盈用
        List<TempKcjlDaily> inventoryBakList =
                BeanCopyUtils.copyListProperties(inventoryList, TempKcjlDaily::new);
        //当日需要处理的销售数据
        List<SellRecordBO> curSellData = sellDeliveryManager
                .dealCurSellDelivery(lastMonthLastDay, sellDeliveryList, allHisBelongsList);
        //销售区分fba、非fba数据
        List<HistoryBelongsBO> hisCkBelongsList = allHisBelongsList.stream()
                .filter(l -> {
                    try {
                        long dateTime = df.parse(l.getHtrq()).getTime();
                        if (dateTime < df.parse(lastMonthLastDay).getTime()) {
                            return true;
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e.getMessage() + ",时间格式化失败！htrq：" + l.getHtrq());
                    }
                    return false;
                })
                .collect(Collectors.toList());
        //非fba所有历史货权信息
        List<HistoryBelongsBO> hisBelongList = hisCkBelongsList.stream()
                .filter(l -> StringUtils.isBlank(fbaCkMap.get(l.getPlace())))
                .collect(Collectors.toList());
        //fba
        List<HistoryBelongsBO> fbaHisBelongList = hisCkBelongsList.stream()
                .filter(l -> StringUtils.isNotBlank(fbaCkMap.get(l.getPlace())))
                .collect(Collectors.toList());
        AtomicInteger deleteFdsXsjl = new AtomicInteger(xsDeleteNum);
        xsDataManager.deductSellData(curSellData, hisBelongList, fbaHisBelongList, inventoryList,
                tempXsjlList, tradeRecordList, tempXsjlAbnormalList, metaWarehouseMap, deleteFdsXsjl);

        //*************** pkpy ***************
        Set<String> sfCkList = RedisUtils.sGet(DICT_PREFIX + CkEnum.SF_CK_LIST.getName());
        List<TempKcjlDaily> minusInventoryList = BeanCopyUtils.copyListProperties(
                inventoryList.stream().filter(l -> l.getSl() < 0 &&
                                !fbaCkMap.containsKey(l.getPlace()) && !sfCkList.contains(l.getPlace()))
                        .collect(Collectors.toList()), TempKcjlDaily::new);
        //对应minusInventoryList数据需要同步删除的销售集合中的数据
        List<TempKcjlDaily> turnPkpyRes = new ArrayList<>();
        List<TempXsjlDelete> tempXsjlDeleteList = new LinkedList<>();
        if (!CollectionUtils.isEmpty(minusInventoryList)) {
            //出库仓库不在fba和sfa。
            List<TempXsjl> excludFbaSfaXsjlList = tempXsjlList.stream().filter(l ->
                    !fbaCkMap.containsKey(l.getChck()) &&
                            !sfCkList.contains(l.getChck())).collect(Collectors.toList());
            Map<String, Map<String, Map<String, Integer>>> minusMap = minusInventoryList.stream()
                    .collect(Collectors.groupingBy(TempKcjlDaily::getPlace,
                            Collectors.groupingBy(TempKcjlDaily::getCpbh,
                                    Collectors.toMap(TempKcjlDaily::getBelongs,
                                            TempKcjlDaily::getSl, Integer::sum))));
            pkpyManager.dealWithMinusInventoryList(deleteFdsXsjl, minusInventoryList,
                    minusMap, metaWarehouseMap, inventoryList, inventoryBakList, tradeRecordList,
                    excludFbaSfaXsjlList, tempXsjlDeleteList);
            turnPkpyRes.addAll(minusInventoryList);
            //盘亏盘盈入库
            pkpyRes.addAll(BeanCopyUtils.copyListProperties(minusInventoryList, TempPkpy::new));
        }
        //fba与sfa需要进行盘亏盘盈数据
        List<TempKcjlDaily> otherMinusInventoryList = inventoryList.stream().filter(l -> l.getSl() < 0 &&
                        (sfCkList.contains(l.getPlace()) || fbaCkMap.containsKey(l.getPlace())))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(otherMinusInventoryList)) {
            turnPkpyRes.addAll(otherMinusInventoryList);
            //盘亏盘盈入库
            pkpyRes.addAll(BeanCopyUtils.copyListProperties(otherMinusInventoryList, TempPkpy::new));
        }
        //总的仓库记录
        List<TempKcjlDaily> allInventoryList = new LinkedList<>();
        finalDataManager.dealJcZyThenPkpy(tempJcjlList, tempZyjlList, turnPkpyRes, inventoryList, pkpyRes);
        finalDataManager.dealFinalData(lastMonthLastDay, inventoryList, allInventoryList, tempXsjlList, tradeRecordList,
                tempXsjlAbnormalList, tempXsjlDeleteList);
        log.info("fds公司删除订单累计" + deleteFdsXsjl.get());
        //
        for (TempPkpy pkpy : pkpyRes) {
            inventoryList.stream().filter(l -> l.getBelongs().equals(pkpy.getBelongs()) &&
                            l.getPlace().equals(pkpy.getPlace()) && l.getCpbh().equals(pkpy.getCpbh()))
                    .forEach(l -> {
                        int sl = Math.max(l.getSl() - pkpy.getSl(), 0);
                        if (sl == 0) {
                            pkpy.setSl(l.getSl());
                        }
                        l.setSl(sl);
                        log.info("扣除盘亏盘盈，" + pkpy.getCpbh() + ": " + pkpy.getSl());
                    });
        }
        //日志
        remark.append("扣除后，现库存数量: \n");
        for (BuyRecordBO bo : addWarehousingList) {
            List<TempKcjlDaily> kcjlList = inventoryList.stream().filter(l -> l.getBelongs().equals(bo.getBelongs()) &&
                            l.getPlace().equals(bo.getPlace()) && l.getCpbh().equals(bo.getCpbh()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(kcjlList)) {
                //用完了，需进行delete
                remark.append(bo.getCpbh()).append("-").append(bo.getPlace()).append("-")
                        .append(bo.getBelongs()).append(":").append("用完/本无该sku的库存; \n");
                tempKcjlDailyRepository.deleteKc(bo, lastMonthLastDay);
            } else {
                if (kcjlList.size() > 1) {
                    log.info("库存条数大于1");
                }
                if (kcjlList.get(0).getSl() == 0) {
                    tempKcjlDailyRepository.deleteKc(bo, lastMonthLastDay);
                } else {
                    remark.append(kcjlList.get(0).getCpbh()).append("-").append(kcjlList.get(0).getPlace()).append("-")
                            .append(kcjlList.get(0).getBelongs()).append(":").append(kcjlList.get(0).getSl()).append("; \n");
                    tempKcjlDailyRepository.updateSl(kcjlList.get(0), lastMonthLastDay);
                }
            }
        }
        String dataDailyLog = "买卖：" + tradeRecordList.size() +
                ",盘亏盘盈：" + pkpyRes.size() + ",退货：0（不影响结果）" + ",销售：" + tempXsjlList.size() +
                ",销售abnormal：" + tempXsjlAbnormalList.size() + ",销售delete：" + tempXsjlDeleteList.size() +
                ",转运delete：" + tempZyjlDeleteList.size() + ",转运：" + tempZyjlList.size() +
                ",转运change：" + zyjlChangeList.size();
        log.info(dataDailyLog + "\n" + remark);

        tempZyjlList.forEach(e -> {
            e.setCreateTime(createTime);
            if (StringUtils.isBlank(e.getHthm())) {
                e.setHthm("");
            }
        });
        tradeRecordList.forEach(e -> {
            e.setCreateTime(createTime);
            e.setDate(lastMonthLastDay);
        });
        pkpyRes.forEach(e -> {
            e.setDate(lastMonthLastDay);
            e.setCreateTime(createTime);
        });
        tempJcjlList.forEach(e -> e.setCreateTime(createTime));
        tempXsjlList.forEach(e -> e.setCreateTime(createTime));
        tempXsjlAbnormalList.forEach(e -> e.setCreateTime(createTime));
        tempXsjlDeleteList.forEach(e -> e.setCreateTime(createTime));
        tempZyjlDeleteList.forEach(e -> e.setCreateTime(createTime));
        addEntityManager.addStkData(tempJcjlList, tempZyjlList, new ArrayList<>(), tradeRecordList,
                pkpyRes, new ArrayList<>(), tempXsjlList, tempXsjlAbnormalList,
                tempXsjlDeleteList, tempZyjlDeleteList, zyjlChangeList);
        tempRestorationMapper.insert(TempRestoration.builder()
                .executeDate(StringUtils.substring(endDate, 0, 7))
                .supplementTime(createTime).remark(remark.toString()).build());
    }

    @Override
    public void beforeZyXsOrder(Integer month) {
//        LocalDate now = LocalDate.now();
//        DateExtUtil.getBeforeNDays()
//        List<SellRecordBO> sellDeliveryList = new LinkedList<>();
//        List<SellRecordBO> sellRecordList = euSourceDataService.getSellRecordListByDate(startDate, endDate);
//        List<String> whIds = euSourceDataService.getWhIdByTimeGet(startDate, endDate);
//        List<SellRecordBO> deliveryGoodsList = euSourceDataService
//                .getDeliveryGoodsListByDate(startDate, endDate, whIds);
//        sellDeliveryManager.getEligibleSellDeliveryData(sellRecordList, deliveryGoodsList,
//                sellDeliveryList, placeMatchDictMap, storeMap, fbaCountryList);
//        sellDeliveryList = sellDeliveryList.stream().distinct().filter(l -> !l.getChck().equals("EU07"))
//                .collect(Collectors.toList());
    }
}
